package code.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import code.web.websocket.ChatWebSocket;

import java.io.IOException;

@Component
public class MessagePubSub {
    public static final String CHANNEL = "chat_channel";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 发送消息到频道
    // 所有订阅客户端都能收到
    public void pubMessage(String message) {
        redisTemplate.convertAndSend(CHANNEL, message);
    }

    // 消息监听容器（需配置）
    // 接收消息,并且广播给本地所有session
    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter((MessageListener) (message, pattern) -> {
            String msg = new String(message.getBody());
            // 收到的内容为json字符串对象,解码成字符串
            Object obj = JSON.parse(msg);
            if (obj instanceof String) {
                msg = (String) obj;
            }
            final String finalMsg = msg;
            // 收到消息,广播给本客户端的所有session
            ChatWebSocket.sessionMap.values().forEach(session -> {
                try {
                    session.getBasicRemote().sendText(finalMsg);
                } catch (IOException ignored) {
                }
            });
        });
    }
}